﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using RemoteDesktops;
using System.Xml;
using System.Runtime.InteropServices;

namespace RemoteDesktops
{
    public partial class Form1 : Form
    {
       
        const string CONNECTION_FILE = "connections.csv";
        bool bSmall = false;
        int oldHeight, oldWidth;

        public Form1()
        {
            InitializeComponent();
            readFile();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            startRdp();
        }

        private void startRdp()
        {
            RemoteDesktopConnection rdp = new RemoteDesktopConnection();
            rdp.username = comboBoxUsername.Text;
            rdp.computer = textBoxComputerName.Text;
            rdp.domain = comboBoxDomain.Text;

            if (radioButton1.Checked == true)
            {
                rdp.width = 1024;
                rdp.height = 768;
            }
            else if (radioButton2.Checked == true)
            {
                rdp.width = 1280;
                rdp.height = 1000;
            }
            else if (radioButton3.Checked == true)
            {
                rdp.width = 1280;
                rdp.height = 1024;
            }
            else if (radioButton4.Checked == true)
            {
                rdp.width = 2560;
                rdp.height = 1000;
            }
            else if (radioButton5.Checked == true)
            {
                rdp.width = 2560;
                rdp.height = 1024;
            }

            rdp.admin = checkBoxAdmin.Checked;
            rdp.span = checkBoxSpan.Checked;

            rdp.run();
            timer1.Interval = 2000;
            timer1.Start();
        }



        private void saveFile()
        {
            FileInfo f = new FileInfo(CONNECTION_FILE);
            StreamWriter sw = f.CreateText();

            // first line is a list of domains
            for (int i = 0; i < comboBoxDomain.Items.Count; i++)
            {
                sw.Write(comboBoxDomain.Items[i].ToString());
                if (i < comboBoxDomain.Items.Count - 1)
                    sw.Write(":");
                else
                    sw.Write("\r\n");
            }

           
            // second line is a list of usernames
            for (int i = 0; i < comboBoxUsername.Items.Count; i++)
            {
                sw.Write(comboBoxUsername.Items[i].ToString());
                if (i < comboBoxUsername.Items.Count - 1)
                    sw.Write(":");
                else
                    sw.Write("\r\n");
            }

            //the other lines are the connections
            foreach (TreeNode tnLocation in treeView1.Nodes)
            {
                foreach (TreeNode tnComputer in tnLocation.Nodes)
                {
                    if (tnComputer.Tag == null) break; //problem
                    RemoteDesktopConnection rdp = (RemoteDesktopConnection)tnComputer.Tag;

                    sw.WriteLine(rdp.location + ":" +
                                 rdp.computer + ":" +
                                 rdp.description + ":" +
                                 rdp.domain + ":" +
                                 rdp.username + ":" + 
                                 rdp.admin + ":" +
                                 rdp.span);
                }
            }
            sw.Close();
        }



        private void readFile()
        {
            treeView1.Nodes.Clear();
            if (!File.Exists(CONNECTION_FILE)) return;
            StreamReader sr;
            RemoteDesktopConnection rdp;
            string s;
            sr = File.OpenText(CONNECTION_FILE);
            string[] cols;

            // first line is a list of domains
            comboBoxDomain.Items.Clear();
            s = sr.ReadLine();
            cols = s.Split(':');
            foreach (string col in cols)
            {
                if (col != "")
                    comboBoxDomain.Items.Add(col);
            }
            // second line is a list of usernames
            comboBoxUsername.Items.Clear();
            s = sr.ReadLine();
            cols = s.Split(':');
            foreach (string col in cols)
            {
                if (col != "")
                    comboBoxUsername.Items.Add(col);
            }

            while (!sr.EndOfStream)
            {
                s = sr.ReadLine();
                
                cols = s.Split(':');
                rdp = new RemoteDesktopConnection();
                rdp.location = cols[0];
                rdp.computer = cols[1];
                rdp.description = cols[2];
                rdp.domain = cols[3];
                rdp.username = cols[4];
                if (cols[5] == "False")
                    rdp.admin = false;
                else
                    rdp.admin = true;
                if (cols[6] == "False")
                    rdp.span = false;
                else
                    rdp.span = true;
                TreeNode nodeToAdd = new TreeNode(rdp.computer + " - " + rdp.description);
                nodeToAdd.Name = rdp.computer;
                nodeToAdd.Tag = rdp;
                TreeNode[] nodes =  treeView1.Nodes.Find(rdp.location, false);
                if (nodes.Length > 0)
                {
                    nodes[0].Nodes.Add(nodeToAdd);
                }
                else
                { //create the location
                    TreeNode locationNode = treeView1.Nodes.Add(rdp.location);
                    locationNode.Name = rdp.location;
                    locationNode.BackColor = Color.LightBlue;
                    locationNode.Nodes.Add(nodeToAdd);
                }
            }
            sr.Close();
            treeView1.Sort();
        }



        private void refreshOpenConnections()
        {
            listBoxOpenConnections.Items.Clear();
            listBoxOpenConnections.Sorted = true;
            desktopWindow[] desktopWindowsCaptions = MyWindowsFunctions.GetDesktopWindowsCaptions();
            foreach (desktopWindow win in desktopWindowsCaptions)
            {
                win.childWindows = MyWindowsFunctions.GetChildWindowsCaptions(win.hWnd);
                if (win.title.EndsWith(" - Remote Desktop"))
                {
                    listBoxOpenConnections.Items.Add(win);
                }
            }
            
        }

        private void listBoxOpenConnections_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int index = this.listBoxOpenConnections.IndexFromPoint(e.Location);

            if (index != System.Windows.Forms.ListBox.NoMatches)
            {
                desktopWindow dw = (desktopWindow)listBoxOpenConnections.Items[index];
              //  dw.poke();
                dw.restore();
            }
        }


        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag == null) return;
            
            RemoteDesktopConnection rdp = (RemoteDesktopConnection)e.Node.Tag;
            textBoxComputerName.Text = rdp.computer;
            textBoxDescription.Text = rdp.description;
            textBoxLocation.Text = rdp.location;

            comboBoxDomain.Text = rdp.domain;
            comboBoxUsername.Text = rdp.username;

            startRdp();
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            timer1.Interval = 500;
            timer1.Start();
        }

        private void Form1_Enter(object sender, EventArgs e)
        {
            timer1.Interval = 500;
            timer1.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            refreshOpenConnections();
            timer1.Stop();
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            readFile();
            refreshOpenConnections();
        }


        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.Tag != null)
            {
                RemoteDesktopConnection rdp = (RemoteDesktopConnection) e.Node.Tag;

                textBoxComputerName.Text = rdp.computer;
                textBoxLocation.Text = rdp.location;
                textBoxDescription.Text = rdp.description;
                comboBoxDomain.Text = rdp.domain;
                comboBoxUsername.Text = rdp.username;
                checkBoxAdmin.Checked = rdp.admin;
                checkBoxSpan.Checked = rdp.span;
                treeView1.SelectedNode = e.Node;

                if (comboBoxDomain.Text == "") 
                    comboBoxDomain.Text = comboBoxDomain.Items[0].ToString();
                if (comboBoxUsername.Text == "")
                    comboBoxUsername.Text = comboBoxUsername.Items[0].ToString();
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.TopMost = true;
            this.BringToFront();
            
            this.Focus();
            this.TopMost = false;
        }
/*
        private void listBoxDomains_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBoxDomains.SelectedItem != null)
                textBoxDomain.Text = listBoxDomains.SelectedItem.ToString();
            listBoxDomains.SelectedIndex = -1;
        }

        private void listBoxUsernames_SelectedValueChanged(object sender, EventArgs e)
        {
            if (listBoxUsernames.SelectedItem != null)
                textBoxUsername.Text = listBoxUsernames.SelectedItem.ToString();
            listBoxUsernames.SelectedIndex = -1;
        }
        */
        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (textBoxLocation.Text == "")
            {
                MessageBox.Show("Need a location");
                //saveFile();
                return;

            }
            if (textBoxComputerName.Text == "")
            {
                MessageBox.Show("Need a computer name");
                //saveFile();
                return;
            }
            //see if a current settings exist in treeview
            TreeNode[] locationNodes =  treeView1.Nodes.Find(textBoxLocation.Text, false);
            if (locationNodes.Length > 0)
            {
                TreeNode[] nodes = locationNodes[0].Nodes.Find(textBoxComputerName.Text, false);
                if (nodes.Length > 0)
                {
                    RemoteDesktopConnection rdp;
                    if (nodes[0].Tag != null)
                    {
                        rdp = (RemoteDesktopConnection)nodes[0].Tag;
                        rdp.location = textBoxLocation.Text;
                        rdp.computer = textBoxComputerName.Text;
                        rdp.description = textBoxDescription.Text;
                        rdp.username = comboBoxUsername.Text;
                        rdp.domain = comboBoxDomain.Text;
                        rdp.admin = checkBoxAdmin.Checked;
                        rdp.span = checkBoxSpan.Checked;
                        nodes[0].Text = rdp.computer + " - " + rdp.description;
                    }
                    else
                    {
                        //problem
                    }

                }
                else
                { // create the node inside this location node.
                    RemoteDesktopConnection rdp;
                    rdp = new RemoteDesktopConnection();
                    rdp.location = textBoxLocation.Text;
                    rdp.computer = textBoxComputerName.Text;
                    rdp.description = textBoxDescription.Text;
                    rdp.username = comboBoxUsername.Text;
                    rdp.domain = comboBoxDomain.Text;
                    rdp.admin = checkBoxAdmin.Checked;
                    rdp.span = checkBoxSpan.Checked;
                    TreeNode nodeToAdd = new TreeNode(rdp.computer + " - " + rdp.description);
                    nodeToAdd.Tag = rdp;
                    nodeToAdd.Name = rdp.computer;
                    locationNodes[0].Nodes.Add(nodeToAdd);
                }
            }
            else
            { // create the location node..
                TreeNode locationNode = treeView1.Nodes.Add(textBoxLocation.Text);
                locationNode.Name = textBoxLocation.Text;
                locationNode.BackColor = Color.LightBlue;

                RemoteDesktopConnection rdp;
                rdp = new RemoteDesktopConnection();
                rdp.location = textBoxLocation.Text;
                rdp.computer = textBoxComputerName.Text;
                rdp.description = textBoxDescription.Text;
                rdp.username = comboBoxUsername.Text;
                rdp.domain = comboBoxDomain.Text;
                rdp.admin = checkBoxAdmin.Checked;
                rdp.span = checkBoxSpan.Checked;
                TreeNode nodeToAdd = new TreeNode(rdp.computer + " - " + rdp.description);
                nodeToAdd.Tag = rdp;
                nodeToAdd.Name = rdp.computer;
                locationNode.Nodes.Add(nodeToAdd);
            }

            saveFile();
        }


        private void treeView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                treeView1.SelectedNode.Remove();
                saveFile();
            }
        }

        private void importrdmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                XmlDocument xmlDoc;
                xmlDoc = new XmlDocument();
                xmlDoc.Load(dlg.FileName);
                XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Connection");
                foreach (XmlNode n in nodeList)
                {
                    RemoteDesktopConnection rdp = new RemoteDesktopConnection();
                    rdp.location = n.ChildNodes.Item(18).InnerText;
                    rdp.description = n.ChildNodes.Item(23).InnerText;
                    rdp.computer = n.ChildNodes.Item(34).InnerText;
                    rdp.username = n.ChildNodes.Item(40).InnerText;

                    TreeNode nodeToAdd = new TreeNode(rdp.computer + " - " + rdp.description);
                    nodeToAdd.Tag = rdp;
                    TreeNode[] nodes = treeView1.Nodes.Find(rdp.location, false);
                    if (nodes.Length > 0)
                    {
                        nodes[0].Nodes.Add(nodeToAdd);
                    }
                    else
                    { //create the location
                        TreeNode locationNode = treeView1.Nodes.Add(rdp.location);
                        locationNode.Name = rdp.location;
                        //Font font = new Font("Arial", 8, FontStyle.Bold);
                        locationNode.BackColor = Color.LightBlue;
                        // locationNode.NodeFont = font;
                        locationNode.Nodes.Add(nodeToAdd);
                    }
                }
                saveFile();
            }

        }
        /*
        private void buttonAddUsername_Click(object sender, EventArgs e)
        {
            listBoxUsernames.Items.Add(textBoxUsername.Text);
        }

        private void buttonAddDomain_Click(object sender, EventArgs e)
        {
            listBoxDomains.Items.Add(textBoxDomain.Text);
        }
        */
        /*
        private void listBoxUsernames_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (listBoxUsernames.SelectedIndex >= 0 )
                    listBoxUsernames.Items.RemoveAt(listBoxUsernames.SelectedIndex);
            }
        }

        private void listBoxDomains_KeyDown(object sender, KeyEventArgs e)
        {
            if (listBoxDomains.SelectedIndex >= 0)
                listBoxDomains.Items.RemoveAt(listBoxDomains.SelectedIndex);
        }
        */
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFile();
        }

        private const int WM_NCLBUTTONDBLCLK = 0xA3;

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case WM_NCLBUTTONDBLCLK:
                    if (alwaysOnTopDblClickTitleBarToolStripMenuItem.Checked)
                        if (bSmall)
                        {
                            bSmall = false;
                            Width = oldWidth;
                            Height = oldHeight;
                            this.MinimumSize = new Size(400, 510);
                            this.fileToolStripMenuItem.Visible = true;
                            FormBorderStyle = FormBorderStyle.Sizable;
                        }
                        else
                        {
                            bSmall = true;
                            oldWidth = Width;
                            oldHeight = Height;
                            this.MinimumSize = new Size(10, 10);
                            Width = 186;
                            Height = 20;
                            this.fileToolStripMenuItem.Visible = false;
                            FormBorderStyle = FormBorderStyle.FixedSingle;
                        } 
                    else
                        if (this.WindowState == System.Windows.Forms.FormWindowState.Maximized)
                            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
                        else if (this.WindowState == System.Windows.Forms.FormWindowState.Normal)
                            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
                    return; 
            }
            base.WndProc(ref m);
        }

        private void alwaysOnTopDblClickTitleBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            alwaysOnTopDblClickTitleBarToolStripMenuItem.Checked = !alwaysOnTopDblClickTitleBarToolStripMenuItem.Checked;
            this.TopMost = alwaysOnTopDblClickTitleBarToolStripMenuItem.Checked;
        }

        private void stopConnectionsFromSleepingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            stopConnectionsFromSleepingToolStripMenuItem.Checked = !stopConnectionsFromSleepingToolStripMenuItem.Checked;
            timerPoke.Enabled = stopConnectionsFromSleepingToolStripMenuItem.Checked;
        }

        private void listBoxUsernames_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        
        private void timerPoke_Tick(object sender, EventArgs e)
        {

            foreach (desktopWindow dwin in listBoxOpenConnections.Items)
            {
                dwin.poke();
            }
        
          
        }

       

        private void saveToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (!comboBoxDomain.Items.Contains(comboBoxDomain.Text))
                comboBoxDomain.Items.Add(comboBoxDomain.Text);
            if (!comboBoxUsername.Items.Contains(comboBoxUsername.Text))
                comboBoxUsername.Items.Add(comboBoxUsername.Text);

            bool saveCurrent = true;
            if (textBoxLocation.Text == "")
            {
                //MessageBox.Show("Need a location");
                saveCurrent = false;

            }
            if (textBoxComputerName.Text == "")
            {
                //MessageBox.Show("Need a computer name");
                saveCurrent = false;
            }

            if (saveCurrent)
            {
                //see if a current settings exist in treeview
                TreeNode[] locationNodes = treeView1.Nodes.Find(textBoxLocation.Text, false);
                if (locationNodes.Length > 0)
                {
                    TreeNode[] nodes = locationNodes[0].Nodes.Find(textBoxComputerName.Text, false);
                    if (nodes.Length > 0)
                    {
                        RemoteDesktopConnection rdp;
                        if (nodes[0].Tag != null)
                        {
                            rdp = (RemoteDesktopConnection)nodes[0].Tag;
                            rdp.location = textBoxLocation.Text;
                            rdp.computer = textBoxComputerName.Text;
                            rdp.description = textBoxDescription.Text;
                            rdp.username = comboBoxUsername.Text;
                            rdp.domain = comboBoxDomain.Text;
                            rdp.admin = checkBoxAdmin.Checked;
                            rdp.span = checkBoxSpan.Checked;
                            nodes[0].Text = rdp.computer + " - " + rdp.description;
                        }
                        else
                        {
                            //problem
                        }

                    }
                    else
                    { // create the node inside this location node.
                        RemoteDesktopConnection rdp;
                        rdp = new RemoteDesktopConnection();
                        rdp.location = textBoxLocation.Text;
                        rdp.computer = textBoxComputerName.Text;
                        rdp.description = textBoxDescription.Text;
                        rdp.username = comboBoxUsername.Text;
                        rdp.domain = comboBoxDomain.Text;
                        rdp.admin = checkBoxAdmin.Checked;
                        rdp.span = checkBoxSpan.Checked;
                        TreeNode nodeToAdd = new TreeNode(rdp.computer + " - " + rdp.description);
                        nodeToAdd.Tag = rdp;
                        nodeToAdd.Name = rdp.computer;
                        locationNodes[0].Nodes.Add(nodeToAdd);
                    }
                }
                else
                { // create the location node..
                    TreeNode locationNode = treeView1.Nodes.Add(textBoxLocation.Text);
                    locationNode.Name = textBoxLocation.Text;
                    locationNode.BackColor = Color.LightBlue;

                    RemoteDesktopConnection rdp;
                    rdp = new RemoteDesktopConnection();
                    rdp.location = textBoxLocation.Text;
                    rdp.computer = textBoxComputerName.Text;
                    rdp.description = textBoxDescription.Text;
                    rdp.username = comboBoxUsername.Text;
                    rdp.domain = comboBoxDomain.Text;
                    rdp.admin = checkBoxAdmin.Checked;
                    rdp.span = checkBoxSpan.Checked;
                    TreeNode nodeToAdd = new TreeNode(rdp.computer + " - " + rdp.description);
                    nodeToAdd.Tag = rdp;
                    nodeToAdd.Name = rdp.computer;
                    locationNode.Nodes.Add(nodeToAdd);
                }
            }
            saveFile();
        }

        private void editConnectionFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe", CONNECTION_FILE);
        }




    }
}
